package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.Merchant;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.service.MerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @PostMapping("/check")
    public Map<String, Object> checkMerchantStatus(@RequestParam String userId) {
        Merchant merchant = merchantService.checkMerchantStatus(userId);
        Map<String, Object> response = new HashMap<>();
        if (merchant != null) {
            response.put("isMerchant", true);
            response.put("businessId", merchant.getBusinessId());
        } else {
            response.put("isMerchant", false);
        }
        return response;
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestParam String businessName,
                                           @RequestParam String businessAddress,
                                           @RequestParam String businessExplain,
                                           @RequestParam BigDecimal starPrice,
                                           @RequestParam BigDecimal deliveryPrice,
                                           @RequestParam(required = false) String remarks,
                                           @RequestParam String userId,
                                           @RequestParam(required = false) MultipartFile businessImg) {
        try {
            Business business = new Business();
            business.setBusinessName(businessName);
            business.setBusinessAddress(businessAddress);
            business.setBusinessExplain(businessExplain);
            business.setOrderTypeId(1);
            business.setStarPrice(starPrice);
            business.setDeliveryPrice(deliveryPrice);
            business.setRemarks(remarks);
            business.setUserId(userId);

            if (businessImg != null && !businessImg.isEmpty()) {
                String imgPath = saveImage(businessImg);
                business.setBusinessImg(imgPath);
            } else {
                business.setBusinessImg("");
            }

            int result = merchantService.saveBusiness(business);
            return result > 0 ? ResponseEntity.ok("商家注册成功")
                              : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("商家注册失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("注册过程中发生错误: " + e.getMessage());
        }
    }

    private String saveImage(MultipartFile file) throws IOException {
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String uploadDir = "/www/wwwroot/http/image/";
        Path path = Paths.get(uploadDir + fileName);
        File directory = new File(uploadDir);
        if (!directory.exists()) directory.mkdirs();
        Files.write(path, file.getBytes());
        return path.toString();
    }
}